/*
 * Created on 2006-2-13
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.hitrust.gs.util.lang;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hitrust.gs.lib.db.GSBaseDAO;

/**
 * @author simonyi
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class IDGeneratorDeliver extends GSBaseDAO{

    /**
     * @param tableName
     * @param orgId
     * @return
     * @throws Exception
     */
    public long generatorProviderID() throws Exception {
       Connection conn = null;
       long value = -1;
       try{
           conn = this.getConnetion();
           conn.setAutoCommit(false);
           value = GenerateID(conn,"DELIVERPROVIDERID",1);
           conn.commit();
       }catch(Exception e){
           try{conn.rollback();}catch(SQLException ee){}
           throw e;
       }finally{
           try{conn.setAutoCommit(true);}catch(SQLException ee){}
           close(conn);
       }
       return value;
        
    }
    
    /**
     * @param tableName
     * @param orgId
     * @return
     * @throws Exception
     */
    public long generatorManufactureID() throws Exception {
       Connection conn = null;
       long value = -1;
       try{
           conn = this.getConnetion();
           conn.setAutoCommit(false);
           value = GenerateID(conn,"DELIVERMANUFACTUREID",1);
           conn.commit();
       }catch(Exception e){
           try{conn.rollback();}catch(SQLException ee){}
           throw e;
       }finally{
           try{conn.setAutoCommit(true);}catch(SQLException ee){}
           close(conn);
       }
       return value;
        
    }
    
	private long GenerateID(Connection conn,String colName,long count) throws Exception{
		PreparedStatement pstmt = null;
		
		long value = 0;

			String sql = "update GS_SEQUENCE set "+colName+" = "+colName+" +? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,Long.toString(count));
			pstmt.executeUpdate();
			conn.commit();

			pstmt.clearParameters();

			sql = "select "+colName+" from GS_SEQUENCE ";
			pstmt = conn.prepareStatement(sql);
			ResultSet rst = pstmt.executeQuery();
			rst.next();
			value = rst.getLong(1);
            pstmt.close();

		
		return value;
	}
	
	/**
	 * 按需要的位数补齐id长度,左补零
	 * @param id 需要补齐长度的id
	 * @param length
	 * @return
	 */
	public String formatID(long id,int length){
	    String buffer = Long.toString(id);
	    int shortLength = length - buffer.length();
	    if(shortLength <= 0)
	        return buffer;
	    StringBuffer sb = new StringBuffer("");
	    for(int i=0;i<shortLength;i++){
	        sb.append("0");
	    }
	    buffer = sb.toString() + buffer;
	    
	    return buffer;
	}
    
}
